﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Security.Cryptography;
using System.IO;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.UI.HtmlControls;

namespace Exhibition.Common.Helper
{
    /// <summary>
    /// 定义一个加密的枚举类型
    /// </summary> 
    /// <summary>
    /// 字符串通用工具
    /// </summary>
    public static class StringUtils
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="drp">控件</param>
        /// <param name="tField">字段</param>
        /// <param name="vField">值</param>
        /// <param name="T">对象</param>
        /// <param name="selectvalue">选中值</param>
        public  static void BindDropdownList(DropDownList drp, string tField, string vField, object T, string selectvalue)
        {
            drp.DataTextField = tField;
            drp.DataValueField = vField;
            drp.DataSource = T;
            drp.DataBind();
            drp.SelectedValue = selectvalue;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="drp"></param>
        /// <param name="tField">字段</param>
        /// <param name="vField">值</param>
        /// <param name="T"></param>
        public static void BindDropdownList(DropDownList drp, string tField, string vField, object T)
        {
            drp.DataTextField = tField;
            drp.DataValueField = vField;
            drp.DataSource = T;
            drp.DataBind(); 
        }


        public static void BindHtmlSelect(HtmlSelect drp, string tField, string vField, object T)
        {
            drp.DataTextField = tField;
            drp.DataValueField = vField;
            drp.DataSource = T;
            drp.DataBind();
        }
        /// <summary>
        /// 存放COOKIE
        /// </summary>
        /// <param name="cur">存放COOKIE的名字Request.Cookies["XTUSER"]</param>
        /// <param name="setu">存放COOKIE 键值cookie.Values.Set("UserName"。。。</param>
        /// <param name="cont">存放VALUE</param>
        public static void SetCookie(string cur,string setu,string cont) {
            HttpCookie cookie =HttpContext.Current.Request.Cookies[cur]; 
            if (cookie == null)
            {
                cookie = new HttpCookie(cur); 
            } 
            cookie.Values.Set(setu,EncodeHelper.Encrypto( cont)); 
            HttpContext.Current.Response.SetCookie(cookie);
        }

        /// <summary>
        /// 获取COOKIE
        /// </summary>
        /// <param name="cur">获取COOKIE的名字Request.Cookies["XTUSER"]</param>
        /// <param name="setu">获取COOKIE 键值cookie.Values.Set("UserName"</param>
        /// <returns></returns>
        public static string GetCookie(string cur,string setu) {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cur];

            if (cookie != null  )
            {
                if (cookie[setu] != "" && cookie[setu]!=null)
                {
                    return EncodeHelper.Decrypto( cookie[setu].ToString());
                }
            }
            return "";

        }



        /// <summary>
        /// 定义一个加密的枚举类型
        /// </summary>
        public enum PassFormat { SHA1, MD5 };
        /// <summary>
        /// 字符串通用工具
        /// </summary>

        /// <summary>
        /// 随机生成字符串源
        /// </summary>
        public const string RANDOM_STRING_SOURCE = "0123456789abcdefghijklmnopqrstuvwxyz";

        /// <summary>
        /// 获取web.config配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetWebConfigValue(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
        /// <summary>
        /// 替换字符串
        /// </summary>
        /// <param name="src">要修改的字符串</param>

        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <returns>已修改的字符串</returns>
        public static string Replace(string src, string pattern, string replacement)
        {
            return Replace(src, pattern, replacement, RegexOptions.None);
        }




        /// <summary>
        /// 替换字符串,不区分大小写
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <returns>已修改的字符串</returns>
        public static string ReplaceIgnoreCase(string src, string pattern, string replacement)
        {
            return Replace(src, pattern, replacement, RegexOptions.IgnoreCase);
        }

        public  static  string UCode(string  ucode)
        {
            if (!string.IsNullOrEmpty(ucode))
            {
                return (Convert.ToInt32(ucode) + 1).ToString();
            }
            else
            {
                return "10001";
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool DeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

    


        /// <summary>
        /// 替换字符串
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要匹配的正则表达式模式</param>
        /// <param name="replacement">替换字符串</param>
        /// <param name="options">匹配模式</param>
        /// <returns>已修改的字符串</returns>
        public static string Replace(string src, string pattern, string replacement, RegexOptions options)
        {
            Regex regex = new Regex(pattern, options | RegexOptions.Compiled);

            return regex.Replace(src, replacement);
        }

        /// <summary>
        /// 删除字符串中指定的内容
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要删除的正则表达式模式</param>
        /// <returns>已删除指定内容的字符串</returns>
        public static string Drop(string src, string pattern)
        {
            return Replace(src, pattern, "");
        }

        /// <summary>
        /// 删除字符串中指定的内容,不区分大小写
        /// </summary>
        /// <param name="src">要修改的字符串</param>
        /// <param name="pattern">要删除的正则表达式模式</param>
        /// <returns>已删除指定内容的字符串</returns>
        public static string DropIgnoreCase(string src, string pattern)
        {
            return ReplaceIgnoreCase(src, pattern, "");
        }

        /// <summary>
        /// 替换字符串到数据库可输入模式
        /// </summary>
        /// <param name="src">待插入数据库的字符串</param>
        /// <returns>可插入数据库的字符串</returns>
        public static string ToSQL(string src)
        {
            if (src == null)
            {
                return null;
            }
            return Replace(src, "'", "''");
        }



        public static double ipToNumber(string sIp)
        {       //计算IP值 v4 in vbscript
            var a = sIp.Split('.');
            double iNumber = 0;
            if (a.Length != 4) return 0;
            for (var i = 0; i < 4; ++i)
                iNumber += Convert.ToInt32(a[i]) * Math.Pow(256, 3 - i);
            return iNumber - 1;
        }


        /// <summary>
        /// 去掉html内容中的指定的html标签
        /// </summary>
        /// <param name="content">html内容</param>
        /// <param name="tagName">html标签</param>
        /// <returns>去掉标签的内容</returns>
        public static string DropHtmlTag(string content, string tagName)
        {
            //去掉<tagname>和</tagname>
            return DropIgnoreCase(content, "<[/]{0,1}" + tagName + "[^\\>]*\\>");
        }

        /// <summary>
        /// 去掉html内容中全部标签
        /// </summary>
        /// <param name="content">html内容</param>
        /// <returns>去掉html标签的内容</returns>
        public static string DropHtmlTag(string content)
        {
            //去掉<*>
            return Drop(content, "<[^\\>]*>");
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="num">字符串的位数</param>
        /// <returns>可插入数据库的字符串</returns>
        public static string GetRandomString(int num)
        {
            string rndStr = "";
            Random rnd = new Random();
            for (int i = 0; i < num; i++)
            {
                rndStr += RANDOM_STRING_SOURCE.Substring(Convert.ToInt32(Math.Round(rnd.NextDouble() * 36, 0)), 1);
            }
            return rndStr;
        }
        /// <summary>
        /// 判断一个数据是不是数字 true为是 false为不是
        /// </summary>
        /// <param name="inputData">字符串</param>
        /// <returns>结果</returns>
        public static bool IsNumeric(string inputData)
        {
            if (inputData != null && inputData.Trim() != "")
            {
                Regex _isNumber = new Regex(@"^\d+$");
                Match m = _isNumber.Match(inputData);
                return m.Success;
            }
            else
                return false;
        }

        /// <summary>
        /// 转换html标签为web页可见内容
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string EscapeHtml(string src)
        {
            if (src == null)
            {
                return null;
            }
            string s = src;
            s = Replace(s, ">", "&gt;");
            s = Replace(s, "<", "&lt;");
            return s;
        }

        /// <summary>
        /// 将字符串格式化成HTML代码
        /// </summary>
        /// <param name="str">要格式化的字符串</param>
        /// <returns>格式化后的字符串</returns>
        public static String ToHtml(string str)
        {
            if (str == null || str.Equals(""))
            {
                return str;
            }

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\r\n", "<br/>");
            sb.Replace("\n", "<br/>");
            sb.Replace("\t", " ");
            sb.Replace(" ", "&nbsp;");
            return sb.ToString();
        }


        /// <summary>
        /// 将HTML代码转化成文本格式
        /// </summary>
        /// <param name="str">要格式化的字符串</param>
        /// <returns>格式化后的字符串</returns>
        public static String ToTxt(String str)
        {
            if (str == null || str.Equals(""))
            {
                return str;
            }

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&nbsp;", " ");
            sb.Replace("<br>", "\r\n");
            sb.Replace("&lt;", "<");
            sb.Replace("&gt;", ">");
            sb.Replace("&amp;", "&");
            return sb.ToString();
        }

        public static int getRequestConvertToInt(string req)
        {
            if (!string.IsNullOrEmpty(req) && IsNumeric(req))
            {
                return Convert.ToInt32(req);
            }
            return 0;
        }
        public static string GetRandomNumber()
        {
            string str = "";
            str = DateTime.Now.ToString("yyyyMMddHHmmss");
            Random random = new Random();
            str = str + random.Next(0x989680, 0x5f5e0ff).ToString();
            random = null;
            return str;
        }
        public static string GetRandWord(int length)
        {
            string str = string.Empty;
            Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }

        /// <summary>
        /// 截取字符串长度
        /// </summary>
        /// <param name="symbol">要截取的字符串</param>
        /// <param name="len">长度</param>
        /// <param name="symbol">后缀符号</param>
        /// <returns></returns>

        public static string getLimitLengthString(string inputString, int len, string symbol)
        {
            if(string.IsNullOrEmpty(inputString))
            {
                return "";
            }
            int tempLen = 0;
            string tempString = "";
            inputString = DropHtmlTag(inputString);
            ASCIIEncoding ascii = new ASCIIEncoding();

            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }

                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }

                if (tempLen > len)
                    break;
            }
            //如果截过则加上半个省略号
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
            if (mybyte.Length > len)
                tempString = tempString.Substring(0, tempString.Length - 3 == 0 ? 1 : tempString.Length - 3) + symbol;

            return tempString;
        }
        public static string CvtDateTime(object date,string format) {

            string rtndate = string.Empty;
            if (date != null) {
                rtndate =Convert.ToDateTime(date.ToString()).ToString(format);
            }

            return rtndate;
        }

        /// <summary>
        /// 正则检查字符是否符合指定格式
        /// </summary>
        /// <param name="pattern">正则表达式</param>
        /// <param name="CheckedString">被检查的字符</param>
        /// <returns>bool</returns>
        public static bool CharacterFormat(string pattern, string CheckedString)
        {
            Regex reg = new Regex(pattern);
            return reg.IsMatch(CheckedString);
        }

        /// <summary>
        /// 将字符串中符合正则表达式中的字符串替换成目标字符串
        /// </summary>
        /// <param name="pattern">正则表达式</param>
        /// <param name="target">目标字符</param>
        /// <param name="ReplaceString">字符串</param>
        /// <returns>string</returns>
        public static string CharacterReplace(string pattern, string target, string ReplaceString)
        {
            if (string.IsNullOrEmpty(ReplaceString))
            {
                return (string)null;
            }
            Regex reg = new Regex(pattern);
            return reg.Replace(ReplaceString, target);
        }

        /// <summary>
        /// 检查是否为数字,不是返回0
        /// </summary>
        /// <param name="number">要被检查的数字</param>
        /// <returns>int</returns>
        public static int NumberCheck(int number)
        {
            if (string.IsNullOrEmpty(number.ToString()))
            {
                return 0;
            }
            if (CharacterFormat(@"[1-9]+\d*", number.ToString()))
            {
                return number;
            }
            else
            {
                return 0;
            }
        }
        public static int NumberCheck(string number)
        {
            if (string.IsNullOrEmpty(number))
            {
                return 0;
            }
            if (CharacterFormat(@"[1-9]+\d*", number))
            {
                return Convert.ToInt32(number);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 检查字符串是否符合Sql 安全标准，如果符合则直接返回，否则剔出不安全因素。
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSafeString(string str)
        {
            if (str == null)
            { return null; }
            else
            {
                string rs = str.Replace("'", "");
                return rs;
            }
        }
        /// <summary>
        /// sha1 加密密码
        /// </summary>
        /// <param name="Pwd">待加密的密码</param>
        /// <returns>加密过后的密码</returns>
        public static string GetDBPassword(string Pwd)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(Pwd, "sha1");
        }

        public static string ConvertToChinese(int x)
        {
            string s = x.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
            string d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
            return Regex.Replace(d, ".", delegate(Match m) { return "负元空零一二三四五六七八九空空空空空空空分角十百千万亿兆京垓秭穰"[m.Value[0] - '-'].ToString(); });
        }



        #region 对字符串进行MD5或SHA1加密操作
        /// <summary>
        /// 对字符串进行MD5或SHA1加密操作
        /// </summary>
        /// <param name="strPassWord">要求加密的字符串</param>
        /// <param name="strPassWordFormat">加密格式，只包含SHA1和MD5两类</param>
        /// <returns>返回加过密的字符串</returns>
        public static string EncryptPassWord(string strPassWord, PassFormat strPassWordFormat)
        {
            switch (strPassWordFormat)
            {
                case PassFormat.SHA1:
                    return FormsAuthentication.HashPasswordForStoringInConfigFile(strPassWord, "SHA1");
                case PassFormat.MD5:
                    return FormsAuthentication.HashPasswordForStoringInConfigFile(strPassWord, "MD5");
                default:
                    return strPassWord;
            }
        }
        #endregion
        #region
        //默认密钥初始化向量
        private static byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xDF, 0x9F };

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encriptString">待加密的字符串</param>
        /// <param name="encKey">加密密钥,要求为8字节</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string Encrypt(string encriptString)
        {
            string encKey = ConfigurationManager.AppSettings["PWDenckey"];
            encKey = encKey.PadRight(8, 'w').Substring(0, 8);
            try
            {
                byte[] bKey = Encoding.GetEncoding("GB2312").GetBytes(encKey);
                byte[] bIV = DESIV;
                byte[] bEncContent = Encoding.GetEncoding("GB2312").GetBytes(encriptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                //用指定的 Key 和初始化向量 (IV) 创建对称数据加密标准 (DES) 加密器对象
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write);
                cStream.Write(bEncContent, 0, bEncContent.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
                // return Encoding.GetEncoding("GB2312").GetString(mStream.ToArray());
            }
            catch
            {
                return encriptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8字节,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string Decrypt(string decryptString, string decryptKey)
        {
            decryptKey = decryptKey.PadRight(8, 'w').Substring(0, 8);
            try
            {
                byte[] bKey = Encoding.GetEncoding("GB2312").GetBytes(decryptKey);
                byte[] bIV = DESIV;
                byte[] bDecContent = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write);
                cStream.Write(bDecContent, 0, bDecContent.Length);
                cStream.FlushFinalBlock();
                return Encoding.GetEncoding("GB2312").GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        #endregion
    }
}
